<?php

class UserController extends FeController {

    public function init() {
        parent::init();
        //get anonymous countries
        if (!Yii::app()->user->getState("current_user")) {
            if (!Yii::app()->user->getState("ipAddress")) {
                $ipAdd = Yii::app()->ipAdd->getInfo();
                $currency = Countries::GetCurrencyByCountryCode($ipAdd->countryCode);
                Yii::app()->user->setState('ipAddress', $ipAdd); //bien nay de su dung cho form dang ky
                Yii::app()->user->setState('currency', $currency);
            }
        }
    }

    public function actionIndex() {
        $this->layout = 'common.layouts.default.temple';
        $this->render('index', array());
    }

    public function allowedActions() {
        return 'index,logout';
    }

    public function actionRegister() {
        $model = new UserCreateFormUser();
        if (isset($_POST['UserCreateFormUser'])) {
            $model->attributes = $_POST['UserCreateFormUser'];
            $model->ipAddress = $_POST['UserCreateFormUser']['ipAddress'];
            if ($model->validate()) {
                $user = new User();
                $user->username = $model->username;
                $user->display_name = $model->displayName;
                $user->password = $model->password;
                $user->email = $model->email;
                $user->created_time = time();
                $user->status = 1;
                if ($user->save()) {
                    $uid = $user->user_id;
                    unset($user);
                    $AuthAssignment = new AuthAssignment();
                    $AuthAssignment->itemname = 'Guest';
                    $AuthAssignment->userid = $uid;
                    $AuthAssignment->scenario = 'create';
                    $AuthAssignment->save();
                    unset($AuthAssignment);

                    $userAdd = new UserAddress();
                    $userAdd->uid = $uid;
                    $userAdd->ipAddress = $model->ipAddress;
                    $userAdd->phone = $model->phone;
                    $userAdd->company = $model->company;
                    $userAdd->street = $model->street;
                    $userAdd->city = $model->city;
                    $userAdd->region = $model->region;
                    $userAdd->zipCode = $model->zipCode;
                    $userAdd->countryCode = $model->countryCode;
                    $userAdd->created = time();
                    $userAdd->modified = time();
                    $userAdd->save();

                    if ($userAdd) {
                        unset($userAdd);
                        $userlogin = new UserLoginForm();
                        $userlogin->username = $model->username;
                        $userlogin->password = $model->password;
                        if ($userlogin->login()) {
                            Yii::app()->user->setFlash('register-success', t('cms', 'Register Successfully!'));
                            Yii::app()->request->redirect(SITE_PATH);
                            exit();
                        }
                    }
                }
            }
        }
        $this->layout = 'common.layouts.default.temple';
        $this->render('register', array('model' => $model));
    }

    public function actionForgetPass() {
        $this->layout = 'common.layouts.default.temple';
        $model = new UserRecoverPassForm();

        if (!Yii::app()->user->getState('current_user')) {
            $email = '';
            if (isset($_POST['UserRecoverPassForm'])) {
                $model->attributes = $_POST['UserRecoverPassForm'];
                if ($model->validate()) {
                    $user = User::model()->find('username=:uid OR email=:email', array(':uid' => $model->email, ':email' => $model->email));
                    if ($user != null) {
                        $emailName = $user['email'];
                        $mail = new Mail();
                        $mail->name = $user['username'];
                        $secureKey = rand_string(30);

                        $subject = "How to reset your password";
                        $link = SITE_PATH . 'user/authentication?uid=' . $user['user_id'] . '&exp=' . (time() + 12 * 60 * 60) . '&secureKey=' . $secureKey;
                        $body = "<table cellspacing='0' cellpadding='0' border='0' style='font:11px Verdana,Arial,Helvetica,sans-serif;color:#333'>
                                            <tr><td>It's easy:";
                        $body.='<ul><li>Click the link below to open a secure browser window</li>
                                    <li>Type new password and submit</li></ul></td></tr>';
                        $body.='<tr><td style="padding: 5px 0;"><a href ="' . $link . '">Reset your password now</a>' . '</td></tr>';
                        $body.='<tr><td><b>Link not working?</b> Copy and paste the one below into your browser:' . '</td></tr>';
                        $body.='<tr><td><a href="' . $link . '">' . $link . '</a></td></tr>';
                        $body.="<tr><td  style='padding: 5px 0;'>This is a one-time login, so it can be used only once. It expires after one day and nothing will happen if it's not used.</td></tr>
                                         </table>";
                        $mail->content = $body;
                        $mail->mail_to = $emailName;
                        $mail->subject = $subject;
                        $mail->sendMail($mail);

                        $user->user_activation_key = $secureKey;
                        $user->save();
                        $email = $emailName;
                    } else {
                        $model->email = html_entity_decode($model->email);
                        Yii::app()->user->setFlash('error-send-mail', "Username or e-mail is invalid");
                        $this->render('forgetpass', array(
                            'model' => $model,
                        ));
                    }
                }
            }
            $this->render('forgetpass', array(
                'model' => $model,
                'email' => $email,
            ));
        } else {
            Yii::app()->request->redirect(SITE_PATH);
            exit;
        }
    }

    public function actionAuthentication() {
        $request = Yii::app()->request;
        $key = $request->getParam('secureKey', '');
        $uid = $request->getParam('uid', 0);
        $expTime = $request->getParam('exp', 0);
        if ($expTime >= time()) {
            $user = User::model()->find('user_id=:uid && user_activation_key=:key', array(':uid' => $uid, ':key' => $key));
            if ($user) {
                Yii::app()->request->redirect(Yii::app()->createUrl('user/resetPass', array('uid' => $uid)));
            } else {
                Yii::app()->request->redirect(Yii::app()->createUrl('user/forgetpass'));
            }
        } else {
            Yii::app()->request->redirect(Yii::app()->createUrl('user/forgetpass'));
        }
    }

    public function actionResetPass() {
        $request = Yii::app()->request;
        $uid = $request->getParam('uid', 0);
        $user = User::model()->find('user_id=:uid', array(':uid' => $uid));
        $user->user_activation_key = '';
        $user->save();

        $model = new UserResetPasswordForm();
        if (isset($_POST['UserResetPasswordForm'])) {
            $arr = $_POST['UserResetPasswordForm'];
            $model->attributes = $arr;
            if ($model->validate()) {
                $user = User::model()->findByPk($uid);
                $user->password = PassHash::hash($arr['password']);
                if ($user->save()) {
                    Yii::app()->request->redirect(SITE_PATH);
                    //Yii::app()->user->setFlash('success-reset-password', 'Ban da cap nhap mat khau thanh cong');
                }
            }
        }

        $this->layout = 'common.layouts.default.temple';
        $this->render('resetpass', array(
            'model' => $model,
        ));
    }

    public function actionUpdateAccount() {
        $this->layout = 'common.layouts.default.temple';
        $this->render('update_account', array(
        ));
    }

    public function actionUpdateEmail() {
        $model = new UserUpdateEmailForm();
        if (isset($_POST['UserUpdateEmailForm'])) {
            $user = User::model()->find('t.`user_id`=:tid', array('tid' => Yii::app()->user->id));
            $model->attributes = $_POST['UserUpdateEmailForm'];
            if ($model->validate()) {
                $user->email = $model->newemail;
                if ($user->save()) {
                    Yii::app()->user->setFlash('success-update-email', 'Update Email thành công');
                    Yii::app()->request->redirect(SITE_PATH . "user/updateEmail");
                }
            }
        }
        $this->layout = 'common.layouts.default.temple';
        $this->render('update_email', array(
            'model' => $model
        ));
    }

    public function actionUpdateAddress() {
        $model = new UserUpdateFromAddress();
        if (isset($_POST['UserUpdateFromAddress'])) {
            $user = User::model()->find('t.`user_id`=:tid', array('tid' => Yii::app()->user->id));
            $useraddress = UserAddress::model()->findByAttributes(array('uid' => Yii::app()->user->id));
            $model->attributes = $_POST['UserUpdateFromAddress'];
            if ($model->validate()) {
                $user->display_name = $model->displayName;
                $user->save();
                $useraddress->phone = $model->phone;
                $useraddress->company = $model->company;
                $useraddress->street = $model->street;
                $useraddress->city = $model->city;
                $useraddress->region = $model->region;
                $useraddress->zipCode = $model->zipCode;
                if ($useraddress->save()) {
                    //Yii::app()->user->hasFlash('updateaddress', 'Update Address success');
                    Yii::app()->request->redirect(SITE_PATH . "user/updateAddress");
                }
            }
        }
        $this->layout = 'common.layouts.default.temple';
        $this->render('update_address', array(
            'model' => $model,
        ));
    }

    public function actionChangePass() {
        $model = new UserChangePassForm();
        if (isset($_POST['UserChangePassForm'])) {
            $user = User::model()->find('t.`user_id`=:tid', array('tid' => Yii::app()->user->id));
            $model->attributes = $_POST['UserChangePassForm'];
            if ($model->validate()) {
                $user->password = PassHash::hash($model->new_password_1);
                if ($user->save()) {
                    Yii::app()->user->setFlash('success-change-password', 'Change password thành công');
                    Yii::app()->request->redirect(SITE_PATH . "user/changePass");
                }
            }
        }
        $this->layout = 'common.layouts.default.temple';
        $this->render('changepass', array(
            'model' => $model,
        ));
    }

    public function actionOrderHistory() {
        $this->layout = 'common.layouts.default.temple';
        $this->render('order_history', array());
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

}
